import navTpl from './tpl/nav.tpl';
import navItemTpl from './tpl/nav_item.tpl';
import './index.scss';

import {
  NavMenu
} from './nav_menu/';

import tools from '../../../utils/tools';

class Nav {
  constructor() {
    this.name = 'headerNav';
    this.navMenu = new NavMenu();
    this.htmlCache = {};
  }

  tpl(data) {
    /**
     console.log(data);
     * (10)[
     *   0: {id: '1', field: 'se', series_name: 'SE', status: '1'},
     *   1: {id: '2', field: 'play', series_name: 'PLAY', status: '1'},
     *   ...,
     *   9: {id: '10', field: 'cc', series_name: 'CC', status: '1'}
     * ]
     */

    let list = '';

    /**
     console.log(this);
     * Nav {
     *   name: 'headerNav', 
     *   navMenu: {name:..., tpl: fn}, 
     *   htmlCache: {…}
     * }
     */

    data.forEach((item) => {
      list += tools.tplReplace(navItemTpl(), {
        field: item.field,
        seriesName: item.series_name
      });
    });

    return tools.tplReplace(navTpl(), {
      navItems: list,
      navMenu: this.navMenu.tpl()
    });
  }

  navMenuMouseIn(e) {
    //e -> 父组件传入的事件代理对象
    /**
     * e.data保存父组件事件绑定传入的两个值phoneDatas, oNav
     * console.log(e.data);
     * {
     *   phoneDatas: Array(21), 
     *   oNav: {name: 'headerNav', navMenu: NavMenu, htmlCache: {…}}
     * }
     */

    /**
     * console.log(this);
     * Header {
         name: 'header', 
         $el: S.fn.init(1), 
         fieldDatas: Array(10), 
         phoneDatas: Array(21), 
         logo: Logo,
         nav: Nav {name: 'headerNav', navMenu: NavMenu, htmlCache: {…}}
         …
        }
     */

    const phoneDatas = e.data.phoneDatas,
      oNav = e.data.oNav;

    //J_navMenu -> ul
    const field = $(this).attr('data-field'),
      $navMenu = $('.J_navMenu');

    // console.log(field);
    //se/play/mix/xiaomi/...

    // console.log(oNav.navMenu.appendMenuCards(phoneDatas));
    //phoneDatas：[{…}, {…}, ...]

    if (!oNav.htmlCache[field]) {
      oNav.htmlCache[field] = oNav.navMenu.appendMenuCards(phoneDatas.filter((item) => {
        return item.field === field;
      }));
    }

    $navMenu.html(oNav.htmlCache[field]);
  }
}

export {
  Nav
};